package com.thinkcms.seo.seo.core.baidu;
import com.thinkcms.core.utils.ApiResult;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.seo.seo.core.HttpCallBack;
import com.thinkcms.seo.seo.core.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BaiDuEngine {

    //  https://blog.csdn.net/weixin_38796720/article/details/88991153
    static String valStr = "xxxxx";

    //static String baiduApi = "https://www.baidu.com/s?wd=" + valStr + "&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg";
    static String baiduApi="https://www.baidu.com/s?wd="+valStr+"&rsv_spt=1&rsv_iqid=0xa68b4ee500dfb885&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&rsv_dl=tb&oq=site%253Awww.lbcms.top&inputT=1021&rsv_t=a757J8%2F2kgqtj35iOfTZUzt2ZVRCSxDwoR88o4Lfan1PVFj2BTnF4inIuC3Lrei8glEu&rsv_n=2&rsv_pq=c557e42500216fa1&rsv_sug3=2&rsv_sug4=1021";
    public static Map<String, Boolean> isRecord(String checkUrl) {
        final Map<String, Boolean> resultMap = new HashMap<>();
        if (Checker.BeNotBlank(checkUrl)) {
            resultMap.put("ok", false);
            String request = baiduApi.replace(valStr, encode(checkUrl));
            OkHttpUtil.getSync(request, new HttpCallBack() {
                @Override
                public void onSuccess(Call call, ApiResult apiResult) {
                    log.info("success!");
                    Object body = apiResult.get("res");
                    if (Checker.BeNotNull(body) && Checker.BeNotBlank(body.toString())) {
                        Boolean containRow = ckHtmlIsContainRow(body.toString(),checkUrl);
                        if(containRow){
                            resultMap.put("ok", true);
                        }
                    }
                }

                @Override
                public void onFailure(Call call, Exception e) {
                    log.error("error!");
                    log.error(e.getMessage());
                }
            });
        }
        return resultMap;
    }


    private static String encode(String u) {
        String url = null;
        try {
            url = URLEncoder.encode(u, "UTF-8").toString();
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return url;
    }

    private static Boolean ckHtmlIsContainRow(String html,String checkUrl) {
        Boolean res = false;
        //log.info(html);
        if (Checker.BeNotBlank(html)) {
            Document doc = Jsoup.parse(html);
            Elements rows = doc.select("div[class=content_none]");
            if(!rows.isEmpty()){
                res = false;
            }else{
                Elements elements=  doc.select("div[class=result c-container]");
                if(!elements.isEmpty()){
                    Elements aeles= elements.first().select("a");
                    if(!aeles.isEmpty()){
                       String href= aeles.first().attr("href");
                       Map<String, String> realUrls=getRealUrl(href);
                        String checkUrlHost = getHost(checkUrl);
                        String realUrlHost = getHost(realUrls.get("realUrl"));
                       boolean record= (realUrls.containsKey("realUrl") && checkUrl.contains(realUrls.get(("realUrl"))))||
                       (checkUrlHost.equals(realUrlHost) && Checker.BeNotBlank(checkUrlHost));
                       if(record){
                            res = true;
                       }
                    }
                }
            }
        }
        return res;
    }

    private static Map<String,String> getRealUrl(String requestUrl){
//       final Map<String,String> realUrls= new HashMap<>(16);
//        OkHttpUtil.getSync(requestUrl, new HttpCallBack() {
//            @Override
//            public void onSuccess(Call call, ApiResult apiResult) {
//                log.info("success!");
//                Object realUrl=apiResult.get("requestUrl");
//                if (Checker.BeNotNull(realUrl) && Checker.BeNotBlank(realUrl.toString())) {
//                     String realUrlStr = realUrl.toString();
//                     realUrls.put("realUrl",realUrlStr);
//                }
//            }
//            @Override
//            public void onFailure(Call call, Exception e) {
//                log.error("error!");
//                log.error(e.getMessage());
//            }
//        });
//        return realUrls;
        // 优化获取真实地址 方法
        Map<String,String> realUrls= new HashMap<>(16);
        Connection.Response res = null;
        int itimeout = 60000;
        try {
            res = Jsoup.connect(requestUrl).timeout(itimeout).method(Connection.Method.GET).followRedirects(false).execute();
            realUrls.put("realUrl", res.header("Location"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return realUrls;
    }

    public static String  getHost(String url){
        String host="";
        if(Checker.BeBlank(url) || url.startsWith("http://127.0.0.1") || url.startsWith("https://127.0.0.1")){
            return host;
        }
        java.net.URL  urls = null;
        try {
            urls = new  java.net.URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if(Checker.BeNotNull(urls)){
            host = urls.getHost();// 获取主机名
        }
        return host;// 结果 blog.csdn.net
    }

}
